package com.audio;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class AudioSplitterByTime {

    public static void main(String[] args) throws UnsupportedAudioFileException, IOException {
        // 输入音频文件
        File inputFile = new File("C:\\Users\\27452\\Desktop\\AudioDemo\\src\\main\\resources\\static\\testTemplate\\test1.wav");

        // 分割时间（毫秒）
        int segmentTimeMs = 500;

        // 获取当前项目文件夹并创建temp文件夹
        String currentDirectory = System.getProperty("user.dir");
        String outputDirectory = Paths.get(currentDirectory, "temp").toString();
        File outputDir = new File(outputDirectory);

        // 如果temp目录不存在，则创建
        if (!outputDir.exists()) {
            outputDir.mkdir();
        }

        // 分割并保存音频，返回文件列表
        List<File> savedFiles = splitAndSaveAudio(inputFile, outputDirectory, segmentTimeMs);

        // 输出保存的文件路径
        for (File savedFile : savedFiles) {
            System.out.println("Saved segment to: " + savedFile.getAbsolutePath());
        }
    }

    public static List<File> splitAndSaveAudio(File inputFile, String outputDirectory, int segmentTimeMs) throws UnsupportedAudioFileException, IOException {
        // 读取音频文件
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputFile);
        AudioFormat format = audioInputStream.getFormat();

        int frameSize = format.getFrameSize(); // 每帧的字节大小
        float sampleRate = format.getSampleRate(); // 采样率
        int channels = format.getChannels(); // 通道数

        System.out.println("Audio Format: " + format);
        System.out.println("Sample Rate: " + sampleRate + " Hz");
        System.out.println("Frame Size: " + frameSize + " bytes");
        System.out.println("Channels: " + channels);

        // 计算窗口大小（样本点数）
        int samplesPerSegment = (int) (sampleRate * (segmentTimeMs / 1000.0));
        int bytesPerSegment = samplesPerSegment * frameSize;

        System.out.println("Samples Per Segment: " + samplesPerSegment);
        System.out.println("Bytes Per Segment: " + bytesPerSegment);

        // 将音频数据读取到字节数组
        byte[] audioBytes = audioInputStream.readAllBytes();

        // 分割成多个段并保存
        List<File> savedFiles = new ArrayList<>();
        for (int i = 0; i + bytesPerSegment <= audioBytes.length; i += bytesPerSegment) {
            byte[] segment = new byte[bytesPerSegment];
            System.arraycopy(audioBytes, i, segment, 0, bytesPerSegment);

            // 生成输出文件名
            String outputFileName = Paths.get(outputDirectory, "segment_" + i / bytesPerSegment + ".wav").toString();

            // 保存分割后的音频文件
            File savedFile = saveSegment(segment, outputFileName, inputFile);
            savedFiles.add(savedFile);
        }

        return savedFiles;
    }

    public static File saveSegment(byte[] segment, String outputFileName, File originalFile) throws IOException, UnsupportedAudioFileException {
        // 获取原始音频格式
        AudioInputStream originalStream = AudioSystem.getAudioInputStream(originalFile);
        AudioFormat format = originalStream.getFormat();

        // 创建输出音频流
        AudioInputStream segmentStream = new AudioInputStream(
                new java.io.ByteArrayInputStream(segment),
                format,
                segment.length / format.getFrameSize()
        );

        // 保存文件
        File outputFile = new File(outputFileName);
        outputFile.getParentFile().mkdirs();  // 确保目录存在
        AudioSystem.write(segmentStream, AudioFileFormat.Type.WAVE, outputFile);
        System.out.println("Segment saved to: " + outputFile.getAbsolutePath());
        return outputFile;
    }
}
